import 'package:dio/dio.dart';
import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart';

void main() async {
  print("start");
  await Spider.getBookDetails("https://www.biquge.com.cn/book/32883/");
  print("stop");
}

class Spider {
  static getBookDetails(String bookUrl) async {
    // 获取书籍的详情信息
    // todo 先查询数据库中是否存了
    Response resp = await Dio().get(bookUrl);
    String data = resp.data;
    // 解析页面元素
    Document documnet = parse(data);
    // 解析book相关信息
    String bookCoverUrl = documnet.querySelector("#fmimg").getElementsByTagName("img")[0].attributes["src"];
    Element mainInfo = documnet.getElementById("maininfo");
    String bookTitle = mainInfo.getElementsByTagName("h1")[0].innerHtml;
    String bookIntro = mainInfo.querySelector("#intro").innerHtml;
    String bookAuthor = mainInfo.getElementsByTagName("p")[0].innerHtml;
    String bookStatuString = mainInfo.getElementsByTagName("p")[1].innerHtml;
    String latestChapter = mainInfo
        .getElementsByTagName("p")[3]
        .getElementsByTagName("a")[0]
        .innerHtml;
    // 推荐阅读信息
    List<Element> recommendReadBooks =
        documnet.getElementById("listtj").getElementsByTagName("a");
    List bookList = [];
    for (var item in recommendReadBooks) {
      bookList.add({
        "url": "https://www.biquge.com.cn" + item.attributes["href"],
        "title": item.innerHtml,
      });
    }
    Map bookInfo = {
      "bookCoverUrl": bookCoverUrl,
      "bookTitle": bookTitle,
      "bookIntro": bookIntro,
      "bookAuthor":
          bookAuthor.replaceAll("&nbsp;", "").split("：").reversed.toList()[0],
      "bookStatuString": bookStatuString
          .split(",")[0]
          .replaceAll("&nbsp;", "")
          .split("：")
          .reversed
          .toList()[0],
      "latestChapter": latestChapter,
      "recommendBooks": bookList
    };
    // 解析章节相关信息
    List<Element> chapterElements =
        documnet.getElementById("list").getElementsByTagName("a");
    List chapterList = [];
    for (var item in chapterElements) {
      chapterList.add({
        "chapterTitle": item.innerHtml,
        "chapterUrl": "https://www.biquge.com.cn" + item.attributes["href"]
      });
    }
    Map result = {"chapterList": chapterList, "bookInfo": bookInfo};
    print(result);
    return result;
  }
}
